package com.lindroy.androidplayer.viewmodels

import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.lindroy.androidplayer.utils.KVUtil
import com.lindroy.androidplayer.utils.SingleLiveEvent
import com.lindroy.androidplayer.utils.mapSingle
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch

/**
 * @author Lin
 * @date 2022/3/7
 * @function
 */
class SearchViewModel : ViewModel() {

    private val startSearchAction = MutableSharedFlow<Unit>()

    private val backAction = SingleLiveEvent<Unit>()

    val editorActionListener = TextView.OnEditorActionListener{v,actionId,event->
        if (actionId == EditorInfo.IME_ACTION_SEARCH){
            startSearch()
        }
        false
    }

    val keyword = MutableLiveData<String>()

    val startSearchListener = startSearchAction.map { keyword.value }

    val backClickListener = backAction.mapSingle {  }

    fun startSearch() {
        if (keyword.value.isNullOrBlank()){
            return
        }
        viewModelScope.launch {
            KVUtil.addSearchHistory(keyword.value.orEmpty())
            startSearchAction.emit(Unit)
        }
    }

    fun onBackClick(){
        backAction.postValue(Unit)
    }

}